package org.jbfilter.hibernate.junit;

import java.util.List;

import org.hibernate.SessionFactory;
import org.jbfilter.core.FilterComponent;
import org.jbfilter.demo.HibernateUtil;
import org.jbfilter.hibernate.FilterHibernate;
import org.jbfilter.hibernate.factory.FilterHibernates;

public class JbFilterHibernateTestUtils {

	public static <T> boolean pass(FilterComponent<T> fcomp, T bean, Class<T> beanClass) {
		Class<T> clazz;
		// if we don't pass the class the bean cannot be null otherwise we cannot filter
		if (beanClass == null) {
			if (bean == null) {
				throw new NullPointerException("If bean is null, the bean class must be NOT null.");
			}
			@SuppressWarnings("unchecked")
			Class<T> cl = (Class<T>) bean.getClass();
			clazz = cl;
		} else { // beanClass is not null
			clazz = beanClass;
		}
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		FilterHibernate<T> filter = FilterHibernates.newFilter(sessionFactory);
		filter.addFilterComponent(fcomp);
		List<T> filtered = filter.filter(clazz);
		return filtered.contains(bean);
	}
}
